package net.skystudio.es.service.impl;

import net.skystudio.es.elastic.repository.SystemLogRepository;
import net.skystudio.es.entity.MixedOrder;
import net.skystudio.es.entity.SystemLog;
import net.skystudio.es.service.SystemLogService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SystemLogServiceImpl implements SystemLogService {

    @Autowired
    private SystemLogRepository systemLogRepository;

    @Override
    public long count() {
        return systemLogRepository.count();
    }

    @Override
    public SystemLog save(SystemLog systemLog) {
        return systemLogRepository.save(systemLog);
    }

    @Override
    public void delete(SystemLog systemLog) {
        systemLogRepository.delete(systemLog);
    }

    @Override
    public Iterable<SystemLog> getAll() {
        return systemLogRepository.findAll();
    }

    @Override
    public List<SystemLog> getByRequester(String requester) {
        List<SystemLog> result = new ArrayList<>();
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("requester", requester);
        Iterable<SystemLog> iterable  = systemLogRepository.search(matchQueryBuilder);
        iterable.forEach(e -> result.add(e));
        return result;
    }

    @Override
    public Page<SystemLog> pageQuery(Integer pageNo, Integer pageSize, String requester) {
        NativeSearchQuery searchQuery =  new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("requester", requester))
                .withPageable(PageRequest.of(pageNo, pageSize))
                .build();
        return systemLogRepository.search(searchQuery);
    }
}
